import * as api from '@/services/report';
import { PageContainer, ProCard, ProFormSelect,  } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Card, Checkbox, Col, Collapse,  Divider,  Radio, RadioChangeEvent, Row, Space, Tabs, Tag,  } from 'antd';
import React, {  useRef, useState } from 'react';
import { useRequest } from 'umi';
const { Panel } = Collapse;
import * as c from '@/services/consts';
import {  UserOutlined } from '@ant-design/icons';
import { CheckboxValueType } from 'antd/es/checkbox/Group';
import { CheckboxChangeEvent } from 'antd/lib/checkbox';
import Paragraph from 'antd/es/typography/Paragraph';
import FlagImage from '@/components/FlagImage';
import * as utils from '@/utils/utils';
import PieChart from '@/components/PieChart';
import TabPane from 'antd/es/tabs/TabPane';
import LineChart from '@/components/LineChart';
import PlotChart from '@/components/PlotChart';

const OrderList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const [checkedMemberLevel, setCheckedMemberLevel] = useState<any>(undefined);
  const [checkedCountry, setCheckedCountry] = useState<any>(undefined);
  const [checkedGroups, setCheckedGroups] = useState<any[]>(undefined);
  const [checkedRegions, setCheckedRegions] = useState<any[]>(undefined);
  const [checkedNetworks, setCheckedNetworks] = useState<any[]>(undefined);
  const [checkAllGroups, setCheckAllGroups] = useState(false);
  const [checkAllRegions, setCheckAllRegions] = useState(false);
  const [checkAllNetworks, setCheckAllNetworks] = useState(false);
  const [monitorData, setMonitorData] = useState<API.VpnServerOnlineIpStatList | undefined>(undefined);
  const [statData, setStatData] = useState<API.IpOnlineStatList | undefined>(undefined);
  const [checkGeoipIsp, setCheckGeoipIsp] = useState(false);


  const loadData = async (
    params: { [key: string]: any },
    sorter?: { [key: string]: any },
    filter?: { [key: string]: any },
  ) => {

    const result = await api.onlineIpStat(params, sorter, filter);
    if (result && result.success) {
      setMonitorData(result);
    } else {
      setMonitorData(undefined);
    }
    
    return Promise.resolve(result);
  };
  
  const loadStatData = async () => {

    const result = await api.onlineIpStatList(undefined, undefined, undefined);
    if (result && result.success) {
      setStatData(result);
    } else {
      setStatData(undefined);
    }
    
    return Promise.resolve(result);
  };

  
  const { loading } = useRequest(async () => {
    return loadStatData();
  });

  const onCheckMemberLevelChange = (e: RadioChangeEvent) => {
    setCheckedMemberLevel(e.target.value);
    
    setCheckedCountry(undefined);

    setCheckedRegions(undefined);
    setCheckAllRegions(false);
    setCheckedNetworks(undefined);
    setCheckAllNetworks(false);
    setCheckedGroups(undefined);
    setCheckAllGroups(false);
  };
  
  const onCheckCountryChange = (e: RadioChangeEvent) => {
    setCheckedCountry(e.target.value);
    
    setCheckedRegions(undefined);
    setCheckAllRegions(false);
    setCheckedNetworks(undefined);
    setCheckAllNetworks(false);
    setCheckedGroups(undefined);
    setCheckAllGroups(false);
  };

  const onCheckRegionChange = (list: CheckboxValueType[]) => {
    setCheckedRegions(list);
    setCheckAllRegions(list.length === monitorData?.regions?.length);
  };
  
  const onCheckNetworkChange = (list: CheckboxValueType[]) => {
    setCheckedNetworks(list);
    setCheckAllNetworks(list.length === monitorData?.networks?.length);
  };
  
  const onCheckGroupChange = (list: CheckboxValueType[]) => {
    setCheckedGroups(list);
    setCheckAllGroups(list.length === monitorData?.reportGroups?.length);
  };
  
  const onCheckAllRegionChange = (e: CheckboxChangeEvent) => {
    setCheckedRegions(e.target.checked ? monitorData?.regions.map((val)=>val.key) : undefined);
    setCheckAllRegions(e.target.checked);
  };
  
  const onCheckAllNetworkChange = (e: CheckboxChangeEvent) => {
    setCheckedNetworks(e.target.checked ? monitorData?.networks.map((val)=>val.key) : undefined);
    setCheckAllNetworks(e.target.checked);
  };
  
  const onCheckAllGroupChange = (e: CheckboxChangeEvent) => {
    setCheckedGroups(e.target.checked ? monitorData?.reportGroups.map((val)=>val.id) : undefined);
    setCheckAllGroups(e.target.checked);
  };
  
  const onChangeTab = (activeKey: string) => {
  };


  let columns: ProColumns<API.VpnServerOnlineIp>[] = [
    {
      title: '分组',
      dataIndex: 'groups',
      width: 400,
      render: (_, record) => {
        // return record.groupNames?.toString()
        // console.log(record.groups);
        return record.groups?.map((ct) => {
          let title = <>{ct.name}[{ct.code}]</>;
          return <>
          {c.getMemberLevelText(ct.memberLevel)}&nbsp;
        <FlagImage flagName={ct.flag} />
        {title}
          </>
        }) 
      }
    },
    {
      title: '名称',
      sorter: true,
      dataIndex: 'serverName',
      width: 400,
    },
    {
      title: 'IP',
      dataIndex: 'ip',
      sorter: true,
      width: 150,
    },
    {
      title: '国家',
      sorter: true,
      width: 150,
      dataIndex: 'ipCountry',
    },
    {
      title: '地区',
      sorter: true,
      dataIndex: 'ipRegion',
    },
    {
      title: '网络',
      sorter: true,
      dataIndex: 'ipNetwork',
    },
    {
      title: 'IP库 ISP',
      sorter: true,
      dataIndex: 'geoipIsp',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 150,
      sorter: true,
    },
  ];


  return (
    <PageContainer loading={loading}>
      <Tabs type='line'  onChange={onChangeTab}>
        <TabPane tab='实时IP在线' key='real_online'>          

      <ProTable<API.VpnServerOnlineIp>
        rowKey="id"
        actionRef={actionRef}
        formRef={formRef}
        // loading={dataLoading}
        search={false}
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        columns={columns}        
        // toolbar={{
        //   multipleLine: true,
        //   // menu: {
        //   //   type: 'tab',
        //   //   activeKey: memberLevel,
        //   //   items: c.MemberLevelOptions,
        //   //   onChange: (key) => {
        //   //     setMemberLevel(key as number);
        //   //   },
        //   // },
        //   // tabs: {            
        //   //   activeKey: eventGenre,
        //   //   items: getCategoryTabs(true),
        //   //   onChange: (key) => {
        //   //     setEventGenre(key)
        //   //   },
            
        //   // },
        // }}
        // toolBarRender={() => {
        //   var toolbarDoms: any[] = [];
        //   return toolbarDoms;
        // }}
        pagination={{
          defaultPageSize: 50,
          pageSizeOptions: ['50', '100', '200', '500', '1000'],
          hideOnSinglePage: false,
        }}
        // dataSource={monitorData?.data}
        request={loadData}
        params={{
          memberLevel: checkedMemberLevel,
          country: checkedCountry,
          regions: checkedRegions,
          networks: checkedNetworks,
          groupIds: checkedGroups,
          geoipIsp: checkGeoipIsp,
        }}
        
        tableExtraRender={(_, data) => (
          <>
          
          <Collapse style={{marginBottom:10}} defaultActiveKey={['22']}>
            <Panel key="22" header={<b>会员级别</b>} >
              <Radio.Group key="ckgMemberLevel" value={checkedMemberLevel} onChange={onCheckMemberLevelChange} style={{width:'100%'}}>
              <Row gutter={24}>
              <Col span={2}>
                <Radio value={undefined} defaultChecked={true}>
                    全部
                </Radio>
              </Col>
              {/* {c.MemberLevelOptions.map((ct)=>{ return <Col span={4}>
                <Radio value={ct.value} style={{marginBottom:10}}>
                  <Tag style={{width:150,backgroundColor:"#fff",border:0,marginLeft:-8,fontSize:14,color:"#333"}}>
                    {ct.label}
                  </Tag>
                </Radio>
              </Col>
            })} */}
            
            {monitorData?.memberLevels?.map((ct)=>{ return <Col span={2}>
                <Radio value={ct.key} style={{marginBottom:10}}>
                  {c.getMemberLevelText(Number(ct.key))}<Tag><UserOutlined /> {ct.value}</Tag>
                </Radio>
              </Col>
            })}

              </Row>
              </Radio.Group>
            </Panel>
          </Collapse>
          
          <Collapse style={{marginBottom:10}} defaultActiveKey={['22']}>
            <Panel key="22" header={<b>国家</b>} >
              <Radio.Group key="ckgCountry" value={checkedCountry} onChange={onCheckCountryChange} style={{width:'100%'}}>
              <Row gutter={24}>
              <Col span={2}>
                <Radio value={undefined} defaultChecked={true}>
                    全部
                </Radio>
              </Col>
              {monitorData?.countrys?.map((ct)=>{ return <Col  span={2}>
                <Radio value={ct.key} style={{marginBottom:10}}>
                  <Space>{ct.key}<Tag><UserOutlined /> {ct.value}</Tag></Space>
                </Radio>
              </Col>
              })}
              </Row>
              </Radio.Group>
            </Panel>
          </Collapse>
          
          <Collapse style={{marginBottom: checkedCountry ? 10 : 0, visibility:checkedCountry ? 'visible' : 'hidden', height:checkedCountry ? '' : 0}} defaultActiveKey={['33']}>
            <Panel key="33" header={<b>地区</b>}>
              <Checkbox onChange={onCheckAllRegionChange} checked={checkAllRegions}>
                全部
              </Checkbox>
              <Divider />
              <Checkbox.Group key="ckgRegions" value={checkedRegions} onChange={onCheckRegionChange} style={{width:'100%'}}>
              <Row gutter={24}>
              {monitorData?.regions?.map((ct)=>{ return <Col span={3}>
                <Checkbox value={ct.key} style={{marginBottom:10}}>{ct.key}<Tag><UserOutlined /> {ct.value}</Tag></Checkbox>
              </Col>
              })}
              </Row>
              </Checkbox.Group>
            </Panel>
          </Collapse>
          
          <Collapse style={{marginBottom: (monitorData?.regions) ? 10 : 0, visibility:(monitorData?.regions) ? 'visible' : 'hidden', height:checkedCountry ? 'auto' : 0 }} defaultActiveKey={['44']}>
            <Panel key="44" header={<b>网络运营商</b>}>
              <Checkbox onChange={onCheckAllNetworkChange} checked={checkAllNetworks}>
                全部
              </Checkbox>
              <Checkbox onChange={(e)=>setCheckGeoipIsp(e.target.checked)} checked={checkGeoipIsp}>
                使用IP库ISP名称
              </Checkbox>
              <Divider />
              <Checkbox.Group key="ckgNetworks" value={checkedNetworks} onChange={onCheckNetworkChange} style={{width:'100%'}}>
              <Row>
              {monitorData?.networks?.map((ct)=>{ return <Col span={6}>
                <Checkbox value={ct.key} style={{marginBottom:10}}>{ct.key}<Tag><UserOutlined /> {ct.value}</Tag></Checkbox>
              </Col>
              })}
              </Row>
              </Checkbox.Group>

              <ProCard style={{width:800}}>
              <PieChart
                data={monitorData?.networks ?? []}
                labelField="key"
                valueField="value"
                height={300}
              />
            </ProCard>

            </Panel>
          </Collapse>
          
          
          <Collapse style={{marginBottom:10 }} defaultActiveKey={['44']}>
            <Panel key="44" header={<b>IP汇报分组</b>}>
              <Checkbox onChange={onCheckAllGroupChange} checked={checkAllGroups}>
                全部
              </Checkbox>
              <Divider />
              <Checkbox.Group key="ckgReportGroups" value={checkedGroups} onChange={onCheckGroupChange} style={{width:'100%'}}>
              <Row>
              {monitorData?.reportGroups?.map((ct)=>{ 
                let title = <>{ct.name}[{ct.code}]</>;
                return <Col span={6}>
                <Checkbox value={ct.id} style={{marginBottom:10}}>
                <Space>
                  <Paragraph copyable={{ text: ct.name}} style={{marginBottom:0}}>
                      {c.getMemberLevelText(ct.memberLevel)}&nbsp;
                      <FlagImage flagName={ct.flag} />
                      {title}
                      <Tag><UserOutlined /> {ct.userCount ? utils.formatNumber(ct.userCount) : '0'}
                      {ct.userLimit ? (
                        <span>/ 
                          <span style={{ color: 'orange', fontWeight: 'bold' }}>
                            {utils.formatNumber(ct.userLimit)}
                          </span>
                        </span>
                      ) : (
                        ''
                      )}
                      </Tag>
                  </Paragraph></Space>  
                </Checkbox>
              </Col>
              })}
              </Row>
              </Checkbox.Group>
            </Panel>
          </Collapse>
          
          <Collapse style={{marginBottom:10 }} defaultActiveKey={['444']}>
            <Panel key="44" header={<b>无IP汇报分组</b>}>
              <Row>
              {monitorData?.unReportGroups?.map((ct)=>{ 
                let title = <>{ct.name}[{ct.code}]</>;
                return <Col span={6}>
                <Space style={{marginBottom:10}}>
                  <Paragraph copyable={{ text: ct.name}} style={{marginBottom:0}}>
                      {c.getMemberLevelText(ct.memberLevel)}&nbsp;
                      <FlagImage flagName={ct.flag} />
                      {title}
                      <Tag><UserOutlined /> {ct.userCount ? utils.formatNumber(ct.userCount) : '0'}
                      {ct.userLimit ? (
                        <span>/ 
                          <span style={{ color: 'orange', fontWeight: 'bold' }}>
                            {utils.formatNumber(ct.userLimit)}
                          </span>
                        </span>
                      ) : (
                        ''
                      )}
                      </Tag>
                  </Paragraph></Space>  
              </Col>
              })}
              </Row>
            </Panel>
          </Collapse>

          </>
        )}
      />
      
        </TabPane>

        <TabPane tab='历史IP在线统计'>

          
        <span style={{color:'#999'}}>*当前统计：[伊朗 - 凌晨3点 - 各类型统计 - 在线用户前10运营商]</span>

          {/* <Card>
          <Row gutter={24}>
            <Col>            
              <ProFormSelect
                name="serverType"
                label="统计国家"
                placeholder="请选择服务器类型"
                allowClear={false}
                initialValue='伊朗'
                options={[{}]}
              />
            </Col>
          </Row>
          <Radio.Group key="ckgMemberLevel" value={checkedMemberLevel} onChange={onCheckMemberLevelChange} style={{width:'100%'}}>
              <Row gutter={24}>
              <Col span={2}>
                <Radio value={undefined} defaultChecked={true}>
                    全部
                </Radio>
              </Col>
              {c.MemberLevelOptions.map((ct)=>{ 
                return <Col span={2}>
                  <Radio value={ct.value} style={{marginBottom:10}}>
                    <Tag style={{width:150,backgroundColor:"#fff",border:0,marginLeft:-8,fontSize:14,color:"#333"}}>
                      {ct.label}
                    </Tag>
                  </Radio>
                </Col>
              })}
              </Row>
              </Radio.Group>
          </Card> */}

        <Collapse style={{marginBottom:10}} defaultActiveKey={['22']}>
          <Panel key="22" header={<><b>会员用户</b></>} >
            <Row gutter={24}>
                {statData?.members?.map((val) => {
                  return <Col span={12}><div><h3>{val.key}</h3>
                  <PlotChart
                    data={val.data}
                    xfield="key"
                    yfield="value"
                    seriesField=""
                    height={100}
                    displayLabel={{}}
                    conversionTag={{}}
                    backColor={undefined}
                  />
                </div></Col>
                })}              
            </Row>
          </Panel>
        </Collapse>
          
        <Collapse style={{marginBottom:10}}>
          <Panel key="33" header={<><b>非会员用户</b></>} >
            <Row gutter={24}>
                {statData?.trials?.map((val) => {
                  return <Col span={12}><div><h3>{val.key}</h3>
                  <PlotChart
                    data={val.data}
                    xfield="key"
                    yfield="value"
                    seriesField=""
                    height={100}
                    displayLabel={{}}
                    conversionTag={{}}
                    backColor={undefined}
                  />
                </div>
              </Col>
                })}
            </Row>
          </Panel>
        </Collapse>

        
        <Collapse style={{marginBottom:10}}>
          <Panel key="44" header={<><b>分组-会员用户</b></>} >
            {statData?.memberGroups?.map((v1) => {
              return <Collapse style={{marginBottom:10}}>
                    <Panel key={`44-${v1.key}`} header={<><b>{v1.key}</b></>} >
                      <Row gutter={24}>                        
                          {v1.data?.map((val) => {
                            return <Col span={12}><div><h3>{val.key}</h3>
                            <PlotChart
                              data={val.data}
                              xfield="key"
                              yfield="value"
                              seriesField=""
                              height={100}
                              displayLabel={{}}
                              conversionTag={{}}
                              backColor={undefined}
                            />
                          </div>
                        </Col>
                          })}
                      </Row>
                    </Panel>
              </Collapse>
            })}
          </Panel>
        </Collapse>

        
        <Collapse style={{marginBottom:10}}>
          <Panel key="55" header={<><b>分组-非会员用户</b></>} >
            {statData?.trialGroups?.map((v1) => {
              return <Collapse style={{marginBottom:10}}>
                    <Panel key={`55-${v1.key}`} header={<><b>{v1.key}</b></>} >
                      <Row gutter={24}>                        
                          {v1.data?.map((val) => {
                            return <Col span={12}><div><h3>{val.key}</h3>
                            <PlotChart
                              data={val.data}
                              xfield="key"
                              yfield="value"
                              seriesField=""
                              height={100}
                              displayLabel={{}}
                              conversionTag={{}}
                              backColor={undefined}
                            />
                          </div>
                        </Col>
                          })}
                      </Row>
                    </Panel>
              </Collapse>
            })}
          </Panel>
        </Collapse>


          
        </TabPane>
      </Tabs>
    </PageContainer>
  );
};

export default OrderList;
